'use client';

import { useSearchParams } from 'next/navigation';
import React, { useState, useEffect, Suspense } from 'react';
import { Card, Row, Col, Typography, Form, Select, Input, InputNumber, Button, Slider, Space, Divider, Tooltip, Upload, message, Switch, Collapse } from 'antd';
import { RedoOutlined, DownloadOutlined, CopyOutlined, SettingOutlined, InboxOutlined, DeleteOutlined, SwapOutlined, ZoomInOutlined, HighlightOutlined, BgColorsOutlined, PictureOutlined } from '@ant-design/icons';
import Image from 'next/image';
import AdminLayout from '../AdminLayout';
import styles from './PostProcessing.module.scss';
import { ExtraSingleImageRequest } from '@/types/base';
import { safeDownloadImage } from '../../../utils/domUtils';
import { useRouter } from 'next/navigation';

// 扩展Window接口以支持ClipboardItem
declare global {
  interface Window {
    ClipboardItem: typeof ClipboardItem;
  }
}

const { Title, Paragraph } = Typography;
const { Option } = Select;
const { Dragger } = Upload;
const { Panel } = Collapse;

// Upscaler类型定义
interface Upscaler {
  name: string;
  model_name: string;
  model_path: string;
  model_url: string;
  scale: number;
}

const resolutionPresets = [
  { label: '1:1 (512×512)', width: 512, height: 512 },
  { label: '3:4 (384×512)', width: 384, height: 512 },
  { label: '4:3 (512×384)', width: 512, height: 384 },
  { label: '16:9 (768×432)', width: 768, height: 432 },
  { label: '9:16 (432×768)', width: 432, height: 768 },
  { label: 'HD (1280×720)', width: 1280, height: 720 },
  { label: 'FHD (1920×1080)', width: 1920, height: 1080 },
];

interface StyleConfig {
  id: string;
  name: string;
  description: string;
  image: string;
  resize_mode: number;
  upscaling_resize: number,
  upscaling_resize_w: number,
  upscaling_resize_h: number,
  upscaling_crop: boolean,
  upscaler_1: string,
  upscaler_2: string,
  extras_upscaler_2_visibility: number,
}

const PostProcessingContent: React.FC = () => {
  const [form] = Form.useForm<StyleConfig>();
  const [sourceImageUrl, setSourceImageUrl] = useState<string | null>(null);
  const [resultImageUrl, setResultImageUrl] = useState<string | null>(null);
  const [isProcessing, setIsProcessing] = useState<boolean>(false);
  const [fileList, setFileList] = useState<any[]>([]);
  const [compareMode, setCompareMode] = useState<boolean>(false);
  const [processingParams, setProcessingParams] = useState<StyleConfig | null>(null);
  const [selectedStyle, setSelectedStyle] = useState<string>('realistic-upscale');
  const [currentStyle, setCurrentStyle] = useState<StyleConfig | null>(null);
  const [resizeMethod, setResizeMethod] = useState<number>(0); // 添加状态跟踪调整方法
  const [styleCards, setStyleCards] = useState<StyleConfig[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [upscalers, setUpscalers] = useState<Upscaler[]>([]); // 添加upscalers状态
  const router = useRouter();
  
  // 滑块状态
  // const [gfpganVisibility, setGfpganVisibility] = useState<number>(0);
  // const [codeformerVisibility, setCodeformerVisibility] = useState<number>(0);
  const [extrasUpscaler2Visibility, setExtrasUpscaler2Visibility] = useState<number>(0);
  const [upscalingResize, setUpscalingResize] = useState<number>(2);

  const searchParams = useSearchParams();

  // 获取upscalers数据
  useEffect(() => {
    const fetchUpscalers = async () => {
      try {
        const response = await fetch('/api/sd/upscalers');
        if (!response.ok) {
          throw new Error('Failed to fetch upscalers');
        }
        const upscalersData: Upscaler[] = await response.json();
        setUpscalers(upscalersData);
      } catch (error) {
        console.error('获取upscalers数据失败:', error);
        message.error('获取upscalers数据失败');
      }
    };

    fetchUpscalers();
  }, []);

  useEffect(() => {
    fetch('/api/license/status').then(async (res) => {
      const result = await res.json();
      if (result.status !== 200) {
        router.push('/');
      }
    }).catch(() => {
      router.push('/');
    });
  }, []);

  // 转换template.json数据为Img2ImgRequest格式
  const convertTemplateToRequest = (templateData: any): StyleConfig => {
    return {
      id: templateData.id,
      name: templateData.name,
      description: templateData.description,
      image: templateData.image,
      resize_mode: templateData.resize_mode,
      upscaling_resize: templateData.upscaling_resize,
      upscaling_resize_w: templateData.upscaling_resize_w,
      upscaling_resize_h: templateData.upscaling_resize_h,
      upscaling_crop: templateData.upscaling_crop,
      upscaler_1: templateData.upscaler_1,
      upscaler_2: templateData.upscaler_2,
      extras_upscaler_2_visibility: templateData.extras_upscaler_2_visibility,
    };
  };

  useEffect(() => {
    const loadTemplateData = async () => {
      try {
        const response = await fetch('/api/templates-db');
        if (!response.ok) {
          throw new Error('Failed to load template data');
        }
        
        const result = await response.json();
        if (!result.success) {
          throw new Error('API returned error');
        }
        
        // 从API的扁平数据结构中过滤出postprocess类型的模板
        const img2imgData = result.data.filter((item: any) => item.type === 'postprocess');
        
        // 转换数据并创建styleCards
        const convertedStyleCards: StyleConfig[] = img2imgData.map((item: any) => convertTemplateToRequest(item));
        
        setStyleCards(convertedStyleCards);
        const dataParam = searchParams.get('data');
        if (dataParam) {
          try {
            const decodedData = JSON.parse(decodeURIComponent(dataParam));
            // 假设 decodedData 是 StyleConfig 类型
            setSelectedStyle(decodedData.id);
            setCurrentStyle(decodedData);
            form.setFieldsValue(decodedData);
            setResizeMethod(decodedData.resize_mode);
            setUpscalingResize(decodedData.upscaling_resize);
            setExtrasUpscaler2Visibility(decodedData.extras_upscaler_2_visibility);
          } catch (error) {
            console.error('解析 data 参数失败:', error);
            loadDefaultStyle(convertedStyleCards);
          }
        } else {
          loadDefaultStyle(convertedStyleCards);
        }
        
      } catch (error) {
        console.error('加载模板数据失败:', error);
        message.error('加载模板数据失败，使用默认配置');
        
        // 使用默认的styleCards作为后备
        const defaultStyleCards: StyleConfig[] = [
          {
            id: 'photo-anime',
            name: '照片动漫化',
            description: '将真实照片转换为动漫风格',
            image: '/text-img/xs.png',
            resize_mode: 0,
            upscaling_resize: 2,
            upscaling_resize_w: 512,
            upscaling_resize_h: 512,
            upscaling_crop: false,
            upscaler_1: 'R-ESRGAN 4x+',
            upscaler_2: 'ESRGAN 4x',
            extras_upscaler_2_visibility: 0,
          }
        ];
        setStyleCards(defaultStyleCards);
      }  finally {
        setIsLoading(false);
      }
    };

    loadTemplateData();
  }, []);

  const loadDefaultStyle = (convertedStyleCards: StyleConfig[]) =>  {
    // 设置默认选中的风格
    if (convertedStyleCards.length > 0) {
      const defaultStyle = convertedStyleCards[0];
      setSelectedStyle(defaultStyle.id);
      
      // 更新表单的默认值
      form.setFieldsValue({
        id: defaultStyle.id,
        resize_mode: defaultStyle.resize_mode,
        upscaling_resize: defaultStyle.upscaling_resize,
        upscaling_resize_w: defaultStyle.upscaling_resize_w,
        upscaling_resize_h: defaultStyle.upscaling_resize_h,
        upscaling_crop: defaultStyle.upscaling_crop,
        upscaler_1: defaultStyle.upscaler_1,
        upscaler_2: defaultStyle.upscaler_2,
        extras_upscaler_2_visibility: defaultStyle.extras_upscaler_2_visibility,
      });
      
      // 更新本地状态
      setCurrentStyle(defaultStyle);
      setResizeMethod(defaultStyle.resize_mode);
      setUpscalingResize(defaultStyle.upscaling_resize);
      setExtrasUpscaler2Visibility(defaultStyle.extras_upscaler_2_visibility);
    }
  }

  const handleProcess = async (values: StyleConfig) => {
    if (!sourceImageUrl) {
      message.warning('请先上传源图片');
      return;
    }

    setIsProcessing(true);
    setProcessingParams(values);
    
    try {
      // 将图片转换为base64（去除data:image部分）
      const base64Image = sourceImageUrl.split(',')[1] || sourceImageUrl;
      
      // 构造发送到API的数据
      const requestData: ExtraSingleImageRequest = {
        image: base64Image,
        resize_mode: values.resize_mode,
        upscaling_resize: values.upscaling_resize,
        upscaling_resize_w: values.upscaling_resize_w,
        upscaling_resize_h: values.upscaling_resize_h,
        upscaling_crop: values.upscaling_crop,
        upscaler_1: values.upscaler_1,
        upscaler_2: values.upscaler_2,
        extras_upscaler_2_visibility: values.extras_upscaler_2_visibility / 100, // 转换为0-1范围
      };

      // 调用API
      const response = await fetch('/api/sd/extra-single-image', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestData)
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      
      // 检查返回的数据是否有图像
      if (data.image) {
        // 将Base64图像数据转换为URL
        setResultImageUrl(`data:image/png;base64,${data.image}`);
      } else {
        message.error('未收到有效的图像数据');
        setResultImageUrl(null);
      }
    } catch (error) {
      console.error('处理图像时出错:', error);
      message.error('处理图像失败，请稍后重试');
      setResultImageUrl(null);
    } finally {
      setIsProcessing(false);
    }
  };

  const handleReprocess = () => {
    if (processingParams) {
      handleProcess(processingParams);
    }
  };

  const handleApplyResolutionPreset = (width: number, height: number) => {
    form.setFieldsValue({ upscaling_resize_w: width, upscaling_resize_h: height });
  };

  const handleRemoveSourceImage = () => {
    setSourceImageUrl(null);
    setFileList([]);
    setResultImageUrl(null);
  };

  const handleStyleSelect = (styleValue: string) => {
    setSelectedStyle(styleValue);

    // 找到选中的风格配置
    const selectedStyleConfig = styleCards.find(style => style.id === styleValue);
    if (selectedStyleConfig) {
      // 自动填充表单字段
      form.setFieldsValue({
        id: styleValue,
        resize_mode: selectedStyleConfig.resize_mode,
        upscaling_resize: selectedStyleConfig.upscaling_resize,
        upscaling_resize_w: selectedStyleConfig.upscaling_resize_w,
        upscaling_resize_h: selectedStyleConfig.upscaling_resize_h,
        upscaling_crop: selectedStyleConfig.upscaling_crop,
        upscaler_1: selectedStyleConfig.upscaler_1,
        upscaler_2: selectedStyleConfig.upscaler_2,
        extras_upscaler_2_visibility: selectedStyleConfig.extras_upscaler_2_visibility,
      });
      
      // 更新本地状态
      setCurrentStyle(selectedStyleConfig);
      setResizeMethod(selectedStyleConfig.resize_mode);
      setUpscalingResize(selectedStyleConfig.upscaling_resize);
      setExtrasUpscaler2Visibility(selectedStyleConfig.extras_upscaler_2_visibility);
    }
  };

  const handleResizeMethodChange = (value: number) => {
    setResizeMethod(value);
    form.setFieldsValue({ resize_mode: value });
  };

  const handleDownloadImage = () => {
    if (!resultImageUrl) {
      message.error('没有可下载的图片');
      return;
    }

    try {
      // 生成文件名：使用当前时间戳和随机数
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
      const randomNum = Math.floor(Math.random() * 1000);
      const fileName = `post-process-result-${timestamp}-${randomNum}.png`;
      
      // 使用安全的下载函数
      safeDownloadImage(resultImageUrl, fileName);
      message.success('图片下载成功');
    } catch (error) {
      console.error('下载图片时出错:', error);
      message.error('下载图片失败，请稍后重试');
    }
  };

  const handleCopyImage = async () => {
    if (!resultImageUrl) {
      message.error('没有可复制的图片');
      return;
    }

    try {
      // 将base64图片转换为Blob
      const response = await fetch(resultImageUrl);
      const blob = await response.blob();
      
      // 检查是否支持Clipboard API
      if (navigator.clipboard && window.ClipboardItem) {
        // 使用现代Clipboard API
        const clipboardItem = new ClipboardItem({
          [blob.type]: blob
        });
        await navigator.clipboard.write([clipboardItem]);
        message.success('图片已复制到剪贴板');
      } else {
        // 降级方案：复制图片URL
        await navigator.clipboard.writeText(resultImageUrl);
        message.success('图片URL已复制到剪贴板');
      }
    } catch (error) {
      console.error('复制图片时出错:', error);
      
      // 如果Clipboard API失败，尝试复制URL
      try {
        await navigator.clipboard.writeText(resultImageUrl);
        message.success('图片URL已复制到剪贴板');
      } catch (fallbackError) {
        console.error('复制URL也失败:', fallbackError);
        message.error('复制失败，请手动保存图片');
      }
    }
  };

  const uploadProps = {
    name: 'file',
    multiple: false,
    fileList: fileList,
    beforeUpload: (file: File) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        message.error('只能上传图片文件!');
        return Upload.LIST_IGNORE;
      }
      
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        message.error('图片大小不能超过10MB!');
        return Upload.LIST_IGNORE;
      }

      // 读取图片并显示预览
      const reader = new FileReader();
      reader.onload = (e) => {
        setSourceImageUrl(e.target?.result as string);
      };
      reader.readAsDataURL(file);

      // 更新文件列表
      setFileList([file]);
      return false; // 阻止自动上传
    },
    onRemove: () => {
      setSourceImageUrl(null);
      setFileList([]);
      setResultImageUrl(null);
    },
    onChange: (info: any) => {
      setFileList(info.fileList.slice(-1)); // 只保留最后一个文件
    },
  };

  const toggleCompareMode = () => {
    setCompareMode(!compareMode);
  };

  return (
    <AdminLayout pageTitle="后期处理">
      <div className={styles.container}>
        <Row gutter={24}>
          {/* 左侧配置表单 */}
          <Col xs={24} lg={12}>
            <Card title="图像后期处理" variant="borderless" className={styles.configCard}>
              {/* 图片上传区域 */}
              <div className={styles.uploadSection}>
                {!sourceImageUrl ? (
                  <Dragger {...uploadProps} className={styles.dragger}>
                    <p className="ant-upload-drag-icon">
                      <InboxOutlined />
                    </p>
                    <p className="ant-upload-text">点击或拖拽图片到此区域上传</p>
                    <p className="ant-upload-hint">
                      支持单个图片文件上传，大小不超过10MB
                    </p>
                  </Dragger>
                ) : (
                  <div className={styles.uploadedImage}>
                    <div className={styles.imageWrapper}>
                      <img src={sourceImageUrl} alt="源图片" />
                      <Button 
                        icon={<DeleteOutlined />} 
                        className={styles.deleteButton}
                        onClick={handleRemoveSourceImage}
                      >
                        移除图片
                      </Button>
                    </div>
                  </div>
                )}
              </div>

              {/* 风格选择卡片 */}
              <div className={styles.styleSection}>
                <div className={styles.styleTitle}>风格选择</div>
                {isLoading ? (
                  <div className={styles.loadingContainer}>
                    <div className={styles.loadingText}>正在加载风格配置...</div>
                  </div>
                ) : (
                  <div className={styles.styleCards}>
                    {styleCards.map((style) => (
                      <div
                        key={style.id}
                        className={`${styles.styleCard} ${selectedStyle === style.id ? styles.selected : ''}`}
                        onClick={() => handleStyleSelect(style.id)}
                      >
                        <div className={styles.styleImage}>
                          <Image
                            src={style.image}
                            alt={style.name}
                            width={200}
                            height={150}
                            className={styles.image}
                            priority
                          />
                          {selectedStyle === style.id && (
                            <div className={styles.selectedOverlay}>
                              <div className={styles.checkmark}>✓</div>
                            </div>
                          )}
                        </div>
                        <div className={styles.styleInfo}>
                          <div className={styles.styleName}>{style.name}</div>
                          <div className={styles.styleDescription}>{style.description}</div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              <Form
                form={form}
                layout="vertical"
                onFinish={handleProcess}
                initialValues={{
                  resize_mode: 0,
                  upscaling_resize: 2,
                  upscaling_resize_w: 512,
                  upscaling_resize_h: 512,
                  upscaling_crop: true,
                  upscaler_1: 'R-ESRGAN 4x+',
                  upscaler_2: 'None',
                  extras_upscaler_2_visibility: 0,
                }}
              >
                {/* 尺寸修改 */}
                <div className={styles.formSection}>
                  <div className={styles.sectionTitle}>
                    <ZoomInOutlined /> 尺寸修改
                  </div>
                  
                  <Form.Item name="resize_mode" label="调整方法">
                    <Select onChange={handleResizeMethodChange}>
                      <Option value={0}>按比例放大</Option>
                      <Option value={1}>指定宽高</Option>
                    </Select>
                  </Form.Item>

                  {/* 根据调整方法显示不同的参数 */}
                  {resizeMethod === 1 ? (
                    <div>
                      <Form.Item label="目标尺寸">
                        <Space direction="vertical" style={{ width: '100%' }}>
                          <Space>
                            <Form.Item name="upscaling_resize_w" noStyle>
                              <InputNumber min={64} max={4096} step={16} addonBefore="宽" />
                            </Form.Item>
                            <span>x</span>
                            <Form.Item name="upscaling_resize_h" noStyle>
                              <InputNumber min={64} max={4096} step={16} addonBefore="高" />
                            </Form.Item>
                          </Space>
                          
                          <div className={styles.presetButtons}>
                            {resolutionPresets.map((preset, index) => (
                              <Button
                                key={index}
                                size="small"
                                onClick={() => handleApplyResolutionPreset(preset.width, preset.height)}
                              >
                                {preset.label}
                              </Button>
                            ))}
                          </div>
                        </Space>
                      </Form.Item>

                      <Form.Item name="upscaling_crop" valuePropName="checked">
                        <Switch checkedChildren="放大后裁剪" unCheckedChildren="保持完整" defaultChecked />
                      </Form.Item>
                    </div>
                  ) : (
                    <Form.Item name="upscaling_resize" label={`放大倍数: ${upscalingResize}x`}>
                      <Slider 
                        min={1} 
                        max={8} 
                        step={0.5}
                        onChange={(value) => setUpscalingResize(value)} 
                      />
                    </Form.Item>
                  )}
                </div>

                {/* 放大算法 */}
                <div className={styles.formSection}>
                  <div className={styles.sectionTitle}>
                    <PictureOutlined /> 处理算法
                  </div>
                  
                  <Form.Item name="upscaler_1" label="主要算法">
                    <Select loading={upscalers.length === 0}>
                      {upscalers.map((upscaler) => (
                        <Option key={upscaler.name} value={upscaler.name}>
                          {upscaler.name}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>

                  <Form.Item name="upscaler_2" label="次要算法">
                    <Select loading={upscalers.length === 0}>
                      {upscalers.map((upscaler) => (
                        <Option key={upscaler.name} value={upscaler.name}>
                          {upscaler.name}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>

                  <Form.Item name="extras_upscaler_2_visibility" label={`次要算法可见度: ${extrasUpscaler2Visibility}%`}>
                    <Slider 
                      min={0} 
                      max={100} 
                      onChange={(value) => setExtrasUpscaler2Visibility(value)} 
                    />
                  </Form.Item>
                </div>

                {/* 面部修复 */}
                {/* <div className={styles.formSection}>
                  <div className={styles.sectionTitle}>
                    <HighlightOutlined /> 面部修复
                  </div>
                  
                  <Form.Item name="gfpganVisibility" label={`GFPGAN 可见度: ${gfpganVisibility}%`}>
                    <Slider 
                      min={0} 
                      max={100} 
                      onChange={(value) => setGfpganVisibility(value)} 
                    />
                  </Form.Item>

                  <Form.Item name="codeformerVisibility" label={`CodeFormer 可见度: ${codeformerVisibility}%`}>
                    <Slider 
                      min={0} 
                      max={100} 
                      onChange={(value) => setCodeformerVisibility(value)} 
                    />
                  </Form.Item>

                  <Form.Item name="codeformerWeight" label="CodeFormer 权重 (0=最大修复, 100=原图)">
                    <Slider 
                      min={0} 
                      max={100} 
                    />
                  </Form.Item>
                </div> */}

                {/* 其他选项 */}
                {/* <div className={styles.formSection}>
                  <div className={styles.sectionTitle}>
                    <SettingOutlined /> 其他选项
                  </div>
                  
                  <Form.Item name="showResults" valuePropName="checked" label="显示处理结果">
                    <Switch defaultChecked />
                  </Form.Item>
                </div> */}

                <Divider />

                <Form.Item>
                  <Button 
                    type="primary" 
                    htmlType="submit" 
                    loading={isProcessing} 
                    block
                    className={styles.generateButton}
                  >
                    处理图像
                  </Button>
                </Form.Item>
              </Form>
            </Card>
          </Col>
          
          {/* 右侧图片预览 */}
          <Col xs={24} lg={12}>
            <Card 
              title="图片预览" 
              variant="borderless" 
              className={styles.previewCard}
              extra={
                <Space>
                  {resultImageUrl && (
                    <Tooltip title="对比模式">
                      <Button 
                        icon={<SwapOutlined />} 
                        onClick={toggleCompareMode}
                        type={compareMode ? 'primary' : 'default'}
                      />
                    </Tooltip>
                  )}
                  <Tooltip title="重新处理">
                    <Button 
                      icon={<RedoOutlined />} 
                      disabled={!resultImageUrl || isProcessing} 
                      onClick={handleReprocess}
                      loading={isProcessing}
                    />
                  </Tooltip>
                  <Tooltip title="下载图片">
                    <Button 
                      icon={<DownloadOutlined />} 
                      disabled={!resultImageUrl} 
                      onClick={handleDownloadImage}
                    />
                  </Tooltip>
                  <Tooltip title="复制图片">
                    <Button 
                      icon={<CopyOutlined />} 
                      disabled={!resultImageUrl} 
                      onClick={handleCopyImage}
                    />
                  </Tooltip>
                </Space>
              }
            >
              {!compareMode ? (
                <div className={styles.imagePreview}>
                  {isProcessing ? (
                    <div className={styles.loadingContainer}>
                      <div className={styles.loadingSpinner}></div>
                      <p>正在处理图像，请稍候...</p>
                    </div>
                  ) : resultImageUrl ? (
                    <img src={resultImageUrl} alt="处理后的图像" className={styles.generatedImage} />
                  ) : (
                    <div className={styles.placeholderImage}>
                      <img 
                        src="/see.png" 
                        alt="预览图标" 
                        style={{ 
                          width: '80px', 
                          height: '80px', 
                          opacity: 0.6,
                          filter: 'brightness(0.8)'
                        }} 
                      />
                      <p>上传源图片并点击"处理图像"按钮开始处理</p>
                    </div>
                  )}
                </div>
              ) : (
                <div className={styles.compareView}>
                  <div className={styles.compareTitle}>处理前后对比</div>
                  <div className={styles.compareImages}>
                    <div className={styles.imageContainer}>
                      <img src={sourceImageUrl || ''} alt="处理前" />
                      <div className={styles.imageLabel}>处理前</div>
                    </div>
                    <div className={styles.imageContainer}>
                      <img src={resultImageUrl || ''} alt="处理后" />
                      <div className={styles.imageLabel}>处理后</div>
                    </div>
                  </div>
                </div>
              )}

              {resultImageUrl && processingParams && !compareMode && (
                <div className={styles.imageInfo}>
                  <Divider>处理参数</Divider>
                  <Row gutter={[16, 8]}>
                    <Col span={12}><strong>调整方法:</strong> {processingParams.resize_mode === 0 ? '按比例放大' : '指定宽高'}</Col>
                    {processingParams.resize_mode === 0 ? (
                      <Col span={12}><strong>放大倍数:</strong> {processingParams.upscaling_resize}x</Col>
                    ) : (
                      <div>
                        <Col span={12}><strong>目标尺寸:</strong> {processingParams.upscaling_resize_w}x{processingParams.upscaling_resize_h}</Col>
                        <Col span={12}><strong>放大后裁剪:</strong> {processingParams.upscaling_crop ? '是' : '否'}</Col>
                      </div>
                    )}
                    <Col span={12}><strong>主要算法:</strong> {processingParams.upscaler_1}</Col>
                    <Col span={12}><strong>次要算法:</strong> {processingParams.upscaler_2}</Col>
                    <Col span={12}><strong>次要算法可见度:</strong> {processingParams.extras_upscaler_2_visibility}%</Col>
                  </Row>
                </div>
              )}
            </Card>
          </Col>
        </Row>
      </div>
    </AdminLayout>
  );
};

const PostProcessing: React.FC = () => {
  return (
    <Suspense fallback={<div style={{ padding: '20px', textAlign: 'center' }}>加载中...</div>}>
      <PostProcessingContent />
    </Suspense>
  );
};

export default PostProcessing;